using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class SkillObject_SwordBounce : SkillObject_Sword
{
    private float bounceSpeed = 15f;
    private int bounceCount;
    private Collider2D[] targetEnemies;
    private Transform nextTarget;
    private List<Transform> selectedTargets=new();

    protected override void Update()
    {
        HandlerSwordComeBack();
        HandlerSwordBounce();
    }

    public void HandlerSwordBounce()
    {
        if (nextTarget == null)
            return;

        transform.position = Vector2.MoveTowards(transform.position, nextTarget.position, bounceSpeed * Time.deltaTime);

        if (Vector2.Distance(transform.position, nextTarget.position) < .75f)
        {
            DamageEnemiesInRedius(transform, 1);
            nextTarget = GetNextTarget();
            bounceCount--;

            if (bounceCount == 0 || nextTarget == null)
            {
                nextTarget = null;
                SetBack();
            }

        }
    }
    public override void SetupSword(Skill_SwordThrow skill_SwordThrow, Vector2 initDirection)
    {
        animator?.SetBool("Spin", true);
        base.SetupSword(skill_SwordThrow, initDirection);

        bounceCount = swordThrowManager.bounceCount;
        bounceSpeed = swordThrowManager.bounceSpeed;
    }
    private Transform GetNextTarget()
    {
        List<Transform> validTargets = GetValidTargets();
        Transform nextTarget = validTargets[Random.Range(0, validTargets.Count)];
        selectedTargets.Add(nextTarget);
        return nextTarget;
    }
    
    private List<Transform> GetValidTargets()
    {
        List<Transform> validTargets = new();
        List<Transform> aliveTargets = GetAliveTargets();
        
        foreach (var aliveTarget in aliveTargets)
        {
            if (aliveTarget != null && selectedTargets.Contains(aliveTarget) == false)
                validTargets.Add(aliveTarget);
        }
        if (validTargets.Count > 0)
        {
            return validTargets;
        }

        else
        {
            selectedTargets.Clear();
            return aliveTargets;
        }
    }

    private List<Transform> GetAliveTargets()
    {
        List<Transform> aliveTargets = new();
        foreach (var targetEnemy in targetEnemies)
        {
            if (targetEnemy != null)
                aliveTargets.Add(targetEnemy.transform);
        }
        return aliveTargets;
    }

    protected override void OnTriggerEnter2D(Collider2D collision)
    {
        if (targetEnemies == null)
        {
            targetEnemies = GetAllTargetEnemies(transform, 10);
            rb.simulated = false;
        }

        DamageEnemiesInRedius(transform, 1);

        if (targetEnemies.Length <= 1 || bounceCount == 0)
            SetBack();
        else
        {
            nextTarget = GetNextTarget();
        }
            
        
    }
}
